<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { use } from 'echarts/core'
import { LineChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  VisualMapComponent,
  MarkLineComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import VChart from 'vue-echarts'
use([
  CanvasRenderer,
  GridComponent,
  LineChart,
  MarkLineComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  VisualMapComponent
])
import type { ProjectInfo, PartsInfo } from './types';
import { Project } from '@/components/projects/Project';
import { ElMessage } from 'element-plus';

const project = new Project()

interface DataItem {
  name: string
  value: [string, number]
}

const projectOption = ref<ProjectInfo[]>([])
const projectId = ref<string>('')
const loading = ref<boolean>(false)
const echartsLoading = ref<boolean>(false)

onMounted(()=>{
  init()
})

// 初始化请求接口
const init = async () => {
  try {
    loading.value = true;
    const resp = await project.getAsync(0, 1000).finally(()=>{
      loading.value = false;
    })
    projectOption.value = resp
  } catch (error) {
    loading.value = false;
    if (error) return ElMessage.error(error || '获取项目列表错误！');
  }
};

// 监听选择项目
const projectChange = (e) => {
  echartsLoading.value = true
  // 假加载
  setInterval(() => {
    echartsLoading.value = false
  }, 2000);
}

function randomData(): DataItem {
  now = new Date(+now + oneDay)
  value = value + Math.random() * 21 - 10
  return {
    name: now.toString(),
    value: [[now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'), Math.round(value)]
  }
}

let data = ref<DataItem[]>([])
let now = new Date(1997, 9, 3)
let oneDay = 24 * 3600 * 1000
let value = Math.random() * 1000
for (var i = 0; i < 1000; i++) {
  data.value.push(randomData())
}

const option = {
  title: {
    text: '搅拌罐实时曲线'
  },
  tooltip: {
    trigger: 'axis',
    formatter: function (params: any) {
      params = params[0]
      var date = new Date(params.name)
      return (
        date.getDate() +
        '/' +
        (date.getMonth() + 1) +
        '/' +
        date.getFullYear() +
        ' : ' +
        params.value[1]
      )
    },
    axisPointer: {
      animation: false
    }
  },
  xAxis: {
    type: 'time',
    splitLine: {
      show: false
    }
  },
  yAxis: {
    type: 'value',
    boundaryGap: [0, '100%'],
    splitLine: {
      show: false
    }
  },
  series: [
    {
      name: 'Fake Data',
      type: 'line',
      showSymbol: false,
      data: data.value,
      markLine: {
        silent: true, // 不响应和触发鼠标事件
        data: [
          {
            yAxis: 900, // 设置水平线的y轴位置
            lineStyle: {
              type: 'solid', // 线型，可以是'solid'、'dashed'、'dotted'
              color: 'green', // 线条颜色
              width: 2 // 线条宽度
            }
          }
        ]
      }
    }
  ]
}

setInterval(function () {
  for (var i = 0; i < 5; i++) {
    data.value.shift()
    data.value.push(randomData())
  }
}, 1000)

const currentLife = ref(300)
const warningLife = ref(300)
const stopLife = ref(365)

const beltStatus = computed(() => {
  if (currentLife.value >= stopLife.value) {
    return 'exception'
  } else if (currentLife.value >= warningLife.value) {
    return 'warning'
  } else {
    return 'success'
  }
})
</script>

<template>
  <main class="main-container" v-loading="loading">
    <div class="search-container">
      <el-text type="info" class="mx-1">项目名称:</el-text>
      <div style="margin-left: 8px">
        <el-select class="project-name" @change="projectChange" style="width: 240px" v-model="projectId">
          <el-option
            v-for="item in projectOption"
            :key="item.id"
            :label="item.projectName"
            :value="item.id"
          />
        </el-select>
      </div>
    </div>
    <div class="content-container" v-loading="echartsLoading">
      <div
        style="
          display: flex;
          flex-direction: column;
          align-items: center;
          position: relative;
          margin-right: 4%;
        "
      >
        <span style="font-size: large; font-weight: bold">罐体使用寿命</span>
        <div style="margin-top: 10px">
          <el-progress type="dashboard" :percentage="80" :status="beltStatus">
            <template #default="{ percentage }">
              <span class="percentage-value">{{ percentage }}%</span>
              <span class="percentage-label">Life</span>
            </template>
          </el-progress>
        </div>
        <div
          style="
            float: right;
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            margin-left: 20px;
            margin-top: 10px;
          "
        >
          <div style="width: 150px">
            <span>当前寿命：{{ currentLife }} day</span>
          </div>
          <div style="margin-top: 10px">
            <span>预警寿命：{{ warningLife }} day</span>
          </div>
          <div style="margin-top: 10px">
            <span>停机寿命：{{ stopLife }} day</span>
          </div>
        </div>
      </div>
      <v-chart style="width: 800px" :option="option"></v-chart>
      <el-card style="width: 400px; height: 600px">
        <template #header> 异常报警信息 </template>
        <span style="color: red">压强波动异常! 波动范围10kpa</span>
        <br />
        <span style="color: red">搅拌罐压强超限，超出阈值2kpa</span>
        <br />
        <span style="color: red">搅拌罐压强偏低，低于阈值1kpa</span>
      </el-card>
    </div>
  </main>
</template>

<style scoped lang="scss">
.main-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 5px;
}

.content-container {
  padding: 30px 30px 20px;
  margin-top: 10px;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-container {
  padding: 30px 30px 20px;
  display: flex;
}
.project-name:focus{
  outline: unset;
}
:deep(.el-select__wrapper:focus){
  outline: unset;
}
</style>
